package com.techstar.common.jackson;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.deser.JodaDateDeserializerBase;
import com.techstar.api.pojo.city.DistrictCongestTrend;

public class TimestampIdDeserializer extends JodaDateDeserializerBase<DateTime>{
	private static final long serialVersionUID = 1L;

	public TimestampIdDeserializer() {
        this(DateTime.class, FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT);
    }

    protected TimestampIdDeserializer(Class<?> type, JacksonJodaDateFormat format) {
        super(type, format);
    }
    
    @Override
    public JodaDateDeserializerBase<?> withFormat(JacksonJodaDateFormat jacksonJodaDateFormat) {
        return new com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer(DateTime.class, jacksonJodaDateFormat);
    }
	
	@Override
	public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		DistrictCongestTrend d = (DistrictCongestTrend)ctxt.getParser().getParsingContext().getCurrentValue();
		if (StringUtils.isBlank(jp.getText())||"null".equals(jp.getText().toLowerCase())) {
			return (DateTime) ctxt.handleUnexpectedToken(this.handledType(), jp.getCurrentToken(), jp, "expected String, Number or JSON Array", new Object[0]);
		}else {
			DateTime createTime = DateTime.parse(jp.getText().trim(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
			d.setTimestampId(createTime.getMillis()+"");
			return createTime;
		}
	}

}
